<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>代码生产</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <style>
        .layui-form-pane .layui-form-label {
            width: 110px;
            padding: 8px 5px;
            height: 38px;
            line-height: 20px;
            border-width: 1px;
            border-style: solid;
            border-radius: 2px 0 0 2px;
            text-align: center;
            background-color: #fafafa;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
<form class="layui-form layui-form-pane" action="" name="frmMain">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-card">
                <div class="layui-card-header">全局设置</div>
                <div class="layui-card-body">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">作者</label>
                                <div class="layui-input-block">
                                    <input type="text" name="author" lay-verify="required" autocomplete="off"
                                           placeholder="作者名称" value="lcc"
                                           class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">代码类型</label>
                                <div class="layui-input-block">
                                    <select name="codeType">
                                        <option value="1" selected>CRUD(无接口)</option>
                                        <option value="2" selected>CRUD(有接口)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
            <div class="layui-card">
                <div class="layui-card-header">包设置</div>
                <div class="layui-card-body">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">设置父包名</label>
                                <div class="layui-input-block">
                                    <input type="text" name="parent" lay-verify="required" autocomplete="off"
                                           placeholder="设置父包名" value="com.lzy.system"
                                           class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">设置父包模块名</label>
                                <div class="layui-input-block">
                                    <input type="text" name="moduleName" lay-verify="required" autocomplete="off"
                                           placeholder="设置父包模块名" value=""
                                           class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="layui-card">
                <div class="layui-card-header">策略</div>
                <div class="layui-card-body">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">表名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="tableName" lay-verify="required" autocomplete="off"
                                           placeholder="表名称多个,间隔" value=""
                                           class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item ">
                                <label class="layui-form-label">导入默认字段</label>
                                <div class="layui-input-block">
                                    <select name="isDefField">
                                        <option value="0">否</option>
                                        <option value="1" selected>是</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                生产代码
            </button>
        </div>
    </div>
</form>
<script src="../../../config/apiUrl.js"></script>
<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script>
    layui.use(['form', 'jquery', 'http', 'popup', 'common', 'toast'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let http = layui.http;
        let common = layui.common;
        let toast = layui.toast;
        const q_tname = common.getUrlParams("tableName")
        const q_parent = common.getUrlParams("parent")
        const q_moduleName = common.getUrlParams("moduleName")
        if(q_tname != null){
            frmMain.tableName.value = q_tname;
            frmMain.parent.value = q_parent;
            frmMain.moduleName.value = q_moduleName;
        }
        function downloadFile(url, fileName) {
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        async function createCodee(data) {
            try {
                let { blob, url, fileName } = await fetchDownload(apiUrlConfig.file.createCodee,"POST",data)    ;
                downloadFile(url, fileName);
            } catch (result) {

            }
        }

        // 封装一个fetch download方法
        async function fetchDownload(fetchUrl, method = "POST", body = null) {
            let loading = layui.layer.load();
            const response = await window.fetch(fetchUrl, {
                method,
                body: body ? JSON.stringify(body) : null,
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                    "X-Requested-With": "XMLHttpRequest",
                    "authorization": http.ajax.getToken()
                },
            });
            if(response.headers.get("content-type").indexOf("application/json")!=-1){
                //抛出错误
                let json_data = await response.json();
                if (json_data.status == 10001) {
                    //字段提示
                    let errorMsg = JSON.parse(result.msg);
                    for (let key in errorMsg) {
                        layer.tips(errorMsg[key], $("[name='" + key + "']").parent(), {
                            tips: [3, '#f56c6c'], time: 5000, tipsMore: true
                        });
                        console.error(key, errorMsg[key])
                    }
                } else if (json_data.status == 403) {
                    const bc = new BroadcastChannel('exitLogin');
                    bc.postMessage("exitLogin")
                }else {
                    toast.error({title: false, message: "代码生产错误"})
                }
                throw new Error(json_data.msg);
            }
            const fileName = getFileName(response);
            const blob = await response.blob();
            const url = URL.createObjectURL(blob);
            toast.success({title: false, message: '代码生成成功，已自动下载'});
            layui.layer.close(loading);
            return { blob, url, fileName }; // 返回blob、download url、fileName
        }
        // 根据response header获取文件名
        function getFileName(response) {
            const disposition = response.headers.get('Content-Disposition');

            // 本例格式是："attachment; filename="img.jpg""
            let fileName = disposition.split('filename=')[1].replaceAll('"', '');

            fileName = decodeURIComponent(fileName);
            return fileName;
        }

        form.on('submit(user-save)', function (data) {
            layer.confirm('确定要生成代码么？', {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                createCodee(data.field)
            });
            return false;
        });
    })
</script>
<script>
</script>
</body>
</html>
